package com.qf.config;

import com.qf.dao.TbPermissionRepository;
import com.qf.dao.TbUserRepository;
import com.qf.pojo.entity.TbUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    TbUserRepository tbUserRepository;
    @Autowired
    TbPermissionRepository tbPermissionRepository;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //通过用户名获取器用户权限
        List<String> permissionList = tbPermissionRepository.findPermissionByUserName(username);
        //建立授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将获取的权限放入授权器中
        simpleAuthorizationInfo.addStringPermissions(permissionList);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String username = (String) authenticationToken.getPrincipal();
        //通过用户名查询该用户是否存在
        TbUser tbUser = tbUserRepository.findByUsername(username);
        if (tbUser != null){
            return new SimpleAuthenticationInfo(username,tbUser.getPassword(), ByteSource.Util.bytes(username),this.getName());
        }
        return null;
    }
}
